package com.easywork.mystery.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.easywork.mystery.entity.Contacts;
import com.easywork.mystery.entity.SysUser;
import com.easywork.mystery.repository.ContactsRepository;

@Transactional
@Service
public class ContactsService {
	@Autowired
	private ContactsRepository contactsRepository;

	public ContactsRepository getContactsRepository() {
		return contactsRepository;
	}

	public Page<Contacts> findAll(SysUser user, Pageable pageable) {
		Contacts contacts = new Contacts();
		contacts.setUserId(user.getId());
		Example<Contacts> example = Example.of(contacts);
		return contactsRepository.findAll(example, pageable);
	}

	// -- 添加联系人
	public void addCon(SysUser user, SysUser contact, String account) {
		Date createtime = new Date();
		Contacts con = new Contacts();
		con.setCreatetime(createtime);
		con.setFri_account(account);
		con.setUserId(user.getId());
		con.setFri_id(contact.getId());
		contactsRepository.save(con);
	}

	// -- 根据联系人名和用户id确定联系人来查询
	public Contacts findOne(SysUser user, String account) {
		Contacts contacts = new Contacts();
		contacts.setUserId(user.getId());
		contacts.setFri_account(account);
		Example<Contacts> example = Example.of(contacts);
		return contactsRepository.findOne(example);
	}

	// -- 根据联系人id删除
	public void delById(Long id) {
		System.out.println(id);
		contactsRepository.delete(id);
	}

	// -- 显示所有联系人
	public List<Contacts> showAll(SysUser user) {
		Contacts contacts = new Contacts();
		contacts.setUserId(user.getId());
		Example<Contacts> example = Example.of(contacts);
		return contactsRepository.findAll(example);
	}

	// -- 显示搜索框联系人
	public List<Contacts> findByKey(SysUser user, String key) {
		String account = "%" + key + "%";
		return contactsRepository.findByFriAccount(account, user.getId());
	}

}